package com.shimao.celnet.payment.controller.api;

import com.baiwang.bop.client.BopException;
import com.baiwang.bop.client.IBopClient;
import com.baiwang.bop.request.impl.invoice.impl.InvoiceInvalidRequest;
import com.baiwang.bop.respose.entity.InvoiceInvalidResponse;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.model.PInvoiceRed;
import com.shimao.celnet.payment.model.request.CallIn_InvoiceInvalidRequest;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.service.PInvoiceRedService;
import com.shimao.celnet.payment.service.apiservice.CallOut_invOpenOutService;
import com.shimao.celnet.payment.util.FinalUtil;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 167发票作废接口
 * 外部系统--》支付平台
 * create stan.ruan by 2017/12/28
 * */
@RestController
@RequestMapping(value = "/invoice")
@Api("接口：inv-167-外部发票作废申请(outInvCancelReqIn) 外部系统 → 支付系统，数据：开票详细信息")
public class CallIn_outInvCancelReqInController {
    protected Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private PInvoiceBlueService pInvoiceBlueService;
    @Autowired
    private PInvoiceRedService pInvoiceRedService;

    @Autowired
    private CallOut_invOpenOutService callOut_invOpenOutService;

    @RequestMapping(value = "/invlid",method = RequestMethod.POST)
    public String invlidInvoice(@RequestBody  @Valid CallIn_InvoiceInvalidRequest InvoiceInvalidRequest, BindingResult result){
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        //对这两个变量已经做了非空验证
        String invoiceGuid = InvoiceInvalidRequest.getReceiptGuid();//获取发票记录guid
        String invoiceType = InvoiceInvalidRequest.getBlueRedType();//获取作废发票类型
        IBopClient client = callOut_invOpenOutService.getClient();
        //获取token
        String token = callOut_invOpenOutService.getToken();
        //声明两个实例变量
        PInvoiceBlue pInvoiceBlue = new PInvoiceBlue();
        PInvoiceRed pInvoiceRed = new PInvoiceRed();
        //判断作废发票的类型，并且设置请求作废接口时所必须的参数
        try {
            if ("blue".equalsIgnoreCase(invoiceType)) {
                pInvoiceBlue = pInvoiceBlueService.getByKey(invoiceGuid);
                //查询结果为空或者已作废
                if(pInvoiceBlue == null || "1".equals(pInvoiceBlue.getInvlidFlg())){
                    retJson = new ResponseJson(ErrorInfoEnum.FAIL_INVILD, "系统没有该发票或者该发票已作废");
                    return retJson.toString();
                }
                //调用后台的请求百望作废的接口
                InvoiceInvalidRequest request = new InvoiceInvalidRequest();
                request.setDeviceType(pInvoiceBlue.getDeviceType());//设备类型 0税控服务器，1税控盘--1
                request.setInvoiceInvalidType("1");//作废类型 0：空白票作废 1：已开票作废--1
                request.setSellerTaxNo(pInvoiceBlue.getSellerTaxNo());//纳税人识别号--20
                request.setInvoiceTypeCode(pInvoiceBlue.getInvoiceTypeCode());//发票种类编码:004:增值税专用发票，007:增值税普通发票，026：增值税电子发票，025：增值税卷式发票 --3
                request.setInvoiceTerminalCode(pInvoiceBlue.getInvoiceYerminalCode());//开票点编码--30
                request.setInvoiceCode(pInvoiceBlue.getInvoiceCode());//发票代码--12
                request.setInvoiceNo(pInvoiceBlue.getInvoiceNo());//发票号码--8
                request.setInvoiceInvalidOperator(pInvoiceBlue.getDrawer());//作废人--32
                InvoiceInvalidResponse response = client.execute(request, token, InvoiceInvalidResponse.class);
                if(response != null){
                    retJson.addBody("receiptGuid",InvoiceInvalidRequest.getReceiptGuid());
                    retJson.addBody("invoiceCode", response.getInvoiceCode());
                    retJson.addBody("invoiceNo",response.getInvoiceNo());
                    retJson.addBody("invoiceInvalidDate",response.getInvoiceInvalidDate());
                    //更新发票
                    pInvoiceBlue.setInvlidFlg(FinalUtil.INVOICE_IVIL_CODE);//作废标志 0 ：未作废（默认） 1：作废
                    pInvoiceBlue.setInvlidTime(String.valueOf(System.currentTimeMillis()));//作废时间
                    pInvoiceBlueService.update(pInvoiceBlue);
                }else{
                    retJson = new ResponseJson(ErrorInfoEnum.FAIL_INVILD, "调用百望接口失败");
                }
            } else {
                pInvoiceRed = pInvoiceRedService.getByKey(invoiceGuid);
                //调用后台的请求百望作废的接口
                //查询结果为空或者已作废
                if(pInvoiceRed == null || "1".equals(pInvoiceRed.getInvlidFlg())){
                    retJson = new ResponseJson(ErrorInfoEnum.FAIL_INVILD, "系统没有该发票或者该发票已作废");
                    return retJson.toString();
                }
                InvoiceInvalidRequest request = new InvoiceInvalidRequest();
                request.setDeviceType(pInvoiceRed.getDeviceType());//设备类型 0税控服务器，1税控盘--1
                request.setInvoiceInvalidType("1");//作废类型 0：空白票作废 1：已开票作废--1
                request.setSellerTaxNo(pInvoiceRed.getSellerTaxNo());//纳税人识别号--20
                request.setInvoiceTypeCode(pInvoiceRed.getInvoiceTypeCode());//发票种类编码:004:增值税专用发票，007:增值税普通发票，026：增值税电子发票，025：增值税卷式发票 --3
                request.setInvoiceTerminalCode(pInvoiceRed.getInvoiceYerminalCode());//开票点编码--30
                request.setInvoiceCode(pInvoiceRed.getInvoiceCode());//发票代码--12
                request.setInvoiceNo(pInvoiceRed.getInvoiceNo());//发票号码--8
                request.setInvoiceInvalidOperator(pInvoiceRed.getDrawer());//作废人--32
                InvoiceInvalidResponse response = client.execute(request, token, InvoiceInvalidResponse.class);
                if(response != null){
                    retJson.addBody("receiptGuid",InvoiceInvalidRequest.getReceiptGuid());
                    retJson.addBody("invoiceCode", response.getInvoiceCode());
                    retJson.addBody("invoiceNo",response.getInvoiceNo());
                    retJson.addBody("invoiceInvalidDate",response.getInvoiceInvalidDate());
                    //更新发票
                    pInvoiceBlue.setInvlidFlg(FinalUtil.INVOICE_IVIL_CODE);//作废标志 0 ：未作废（默认） 1：作废
                    pInvoiceBlue.setInvlidTime(String.valueOf(System.currentTimeMillis()));//作废时间
                    pInvoiceBlueService.update(pInvoiceBlue);
                }else{
                    retJson = new ResponseJson(ErrorInfoEnum.FAIL_INVILD, "调用百望接口失败");
                }
            }
        }catch (BopException e){
            log.info("访问失败");
            log.info(e.getErrCode());
            log.info(e.getErrMsg());
            log.info(e.getMessage());
            retJson.setErrorCode(e.getErrCode());
            retJson.setErrorMessage(e.getSubMessage());
        }finally{
            return retJson.toString();
        }
    }
}
